﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using IPMsgMoTest.ViewModels;
using Microsoft.Phone.Shell;

namespace IPMsgMoTest
{
    public partial class ChatPage : PhoneApplicationPage
    {
        public ChatPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            DataContext = ViewManager.Instance.GetChatViewModel(NavigationContext.QueryString["hostname"]);
            //导向至该页面，则通知ChatViewModel处于阅读状态
            (this.DataContext as ChatViewModel).IsReading = true;
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            //离开此页面，则通知ChatViewModel处于非阅读状态
            (this.DataContext as ChatViewModel).IsReading = false;
            base.OnNavigatedFrom(e);
        }

        private void appbar_btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.textBlockContent.Text != string.Empty)
                {
                    IPMSG.IPMsgManager.Instance.SendMsg((this.DataContext as ChatViewModel).Hostname, this.textBlockContent.Text);
                    ViewManager.Instance.HandleSendMsg((this.DataContext as ChatViewModel).Hostname, this.textBlockContent.Text);
                    this.textBlockContent.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("发送失败，原因：{0}", ex.Message));
            }
        }

        private void appbar_btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                (this.DataContext as ChatViewModel).ChatItems.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("清空内容失败，原因：{0}", ex.Message));
            }
        }

        private void appbar_btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                ViewManager.Instance.RemoveChatViewModel((this.DataContext as ChatViewModel).Hostname);
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                CommonUtility.Log.Error(string.Format("关闭聊天窗口失败，原因：{1}", ex.Message));
            }
        }
    }
}